package com.kaifamiao.jdbc.features;

import java.sql.*;

/**
 * 该类测试 可滚动结果集的 可更新特性(并发特性)
 * 通过修改 可滚动结果集 中 指定行的数据来影响数据库中的数据
 */
public class ResultSetUpdatable1 {

    public static void show( ResultSet rs ) throws SQLException {
        int id = rs.getInt( "id" );
        String name = rs.getString( "name" );
        System.out.printf("%d, %s\n", id, name );
    }

    public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException{

        /*
        String driverClassName = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/kaifamiao?serverTimezone=Asia/Chongqing";
        String username = "kfm";
        String password = "kfm";
        */

        String driverClassName = "oracle.jdbc.OracleDriver";
        String url = "jdbc:oracle:thin:@localhost:1521:kaifamiao";
        String username = "kaifamiao";
        String password = "kaifamiao";

        Class.forName( driverClassName );
        Connection conn = DriverManager.getConnection( url, username, password );
        // 关闭事务自动提交
        conn.setAutoCommit( false );

        final String sql = "SELECT id, name FROM t_pandas ORDER BY id";
        final int type = ResultSet.TYPE_SCROLL_SENSITIVE; // 滚动特性: 可滚动、敏感
        final int concurrency = ResultSet.CONCUR_UPDATABLE; // 并发特性: 可更新

        PreparedStatement ps = conn.prepareStatement( sql, type, concurrency );

        ResultSet rs = ps.executeQuery();

        // 绝对定位到第二行
        boolean exists = rs.absolute( 2 );
        if( exists ) {
            show( rs );
            // 修改结果集中的数据
            // rs.updateString( 2 , "大菲"); // 修改当前行第二列的值
            rs.updateString( "name" , "大菲"); // 修改当前行 name 的值
            // ⽤此 ResultSet 对象的当前⾏的新内容更新底层数据库
            rs.updateRow();
            show( rs );
        }

        Thread.sleep( 10000 );

        conn.commit();

        rs.close();

        // 启用事务自动提交
        conn.setAutoCommit( true );

        conn.close();

    }

}
